import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Table,Icon, Select, Radio } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';
import DataRank from './DataRank';
// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      console.log("submit fields ", fieldsValue)

      // 如果更新成功之后，重置表单
      handleSubmit(fieldsValue).then((success:any) => {
        console.log('handleSubmit then success is ', success)
        if(success){
          form.resetFields()
          setPicture([])
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.file_url)
  const [dataAboutFormValues, setDataAboutFormValues] = useState({});
  const [dataAboutModalVisible, handleAboutDataModalVisible] = useState<boolean>(false);

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const columns = [
    {
        title: '接口名称',
        dataIndex: 'apiName',
    },
    {
        title: '接口地址',
        dataIndex: 'apiAddress',
    },
    {
        title: '数据来源',
        dataIndex: 'postLists',
        render: (value, record) => (
            <Select defaultValue={value?.toString()} style={{width:'100%'}} onChange={async (e:any) => {
            //  let s = await handleUpdate({id: record.id, content_mode: e.toString()});
            //  s && actionRef.current?.reload();
           }}>
                {common.restfulPlugin && TsxHelper.buildSelectOption(common.restfulPlugin)}
            </Select>
         )
    },
    {
        title: '排序编号',
        dataIndex: '',
        render: (_, record) => (
            <Button type="primary" onClick={()=>{handleAboutDataModalVisible(true);setDataAboutFormValues(record)}}>配置</Button>
        )
    },
];
  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={'数据来源'}
    width={DataHelper.DEFAULT_MODAL_WIDTH}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >
 <Table 
                style={{backgroundColor: "#fff"}}
                columns={columns}
                dataSource={dataFormValues.source_parameter}
                pagination={false}
            />
            <DataRank
                dataModalVisible={dataAboutModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataAboutFormValues}
                common={common || {}}
                // onSubmit={async formValue => handleSubmitDataForm(formValue)}
                onCancel={() => handleAboutDataModalVisible(false)}
            />
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
